//
//  ComposeViewController.swift
//  SinaWeiBoProject
//
//  Created by 房城鸿 on 15/10/16.
//  Copyright © 2015年 房兰峰. All rights reserved.

import UIKit
import SVProgressHUD


private let HStatausTextMaxLenght = 10

// 撰写微博控制器
class ComposeViewController: UIViewController,UITextViewDelegate {
    
    //MARK: - 表情键盘
    //表情键盘控制器 -- 注意: 如果闭包中调用 self. 函数，同样会做 copy ,需要注意循环引用问题
    private lazy var keyboardVc:EmoticonViewController = EmoticonViewController { [weak self](emoticon) -> () in
        //        print(emoticon.chs)
        self?.textView.insertEmoticon(emoticon)
    }
    
    ///  切换到表情键盘
    @objc private func switchEmoticonKeyboard(){
        //inputView = nil 表示的时系统键盘
        printLog(textView.inputView)
        
        // 注销焦点 --》》 怎么切换键盘 ： 先注销 
        textView.resignFirstResponder()
        
        // 切换键盘
        textView.inputView = (textView.inputView == nil) ? keyboardVc.view : nil
        
        //激活键盘
        textView.becomeFirstResponder()
    }
    
    //MARK:  -控件动画约束
    /// 工具栏底部约束
    private var toolbarBottomCons:NSLayoutConstraint?
    
    /// 文本视图底部约束
    private var textViewBootomCons:NSLayoutConstraint?
    
    //照片选择视图的高度约束
    private var pictureViewHeightCons:NSLayoutConstraint?

    
    //MARK: - 监听方法
    @objc private func close(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // 发送微博
    @objc private func sendStatus(){
        
        //1.获取带表情符号的文本字符串
        let text = textView.emoticonText
        
        //2.判断文本长度
        if text.characters.count > HStatausTextMaxLenght{
            
            SVProgressHUD.showInfoWithStatus("输入的长度过长",maskType:.Gradient)
            return
        }
        
        //发送微博
        NetworkTools.sharedTools.sendStatus(text,image: pictureSelectorVC.picture.last).subscribeNext({ (result) -> Void in
            //printLog(result)
            }, error: { (error) -> Void in
                printLog(error)
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
            }) { () -> Void in
                self.close()
                printLog("OK")
        }
    }
    //MARK: - 添加监听方法
    @objc private func selectPicture(){
        
        printLog("选择照片")
        
        //1, 删除文本视图 和toolbar 之间的约束
        view.removeConstraint(textViewBootomCons!)
        
        //2. 设置文本视图和照片之间的约束
        //MARK: - 切记，这里是 pictureSelectorVC.view  不能漏掉后面的view
        textViewBootomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: pictureSelectorVC.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        
        view.addConstraint(textViewBootomCons!)
    }
    
    //MARK: - UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        //UIKeyInput  ---> public func hasText()
        // 当textView 开始输入文字的时候，占位文字隐藏
        placeholderLabel.hidden = textView.hasText()
        // 让导航栏右侧的可以进行点击，
        navigationItem.rightBarButtonItem?.enabled = true
        
        // 修改文字长度提示
        // 计算字符串的长度
        let len  = HStatausTextMaxLenght - textView.emoticonText.characters.count
        // 将数字转换为 字符串
        lengthTipLabel.text = String(len)
        //颜色提示
        lengthTipLabel.textColor = len >= 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
    
    //MARK: - 视图声明周期函数
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册键盘通知  - UIWindow.h 中的倒数第二个
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit{
        //注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //监听 键盘变化
    @objc private func keyboardChanged(n:NSNotification){
        printLog(n)
        
        /// 获取动画曲线数值 -7  苹果没有提供文档
        //如果动画 曲线设置为 7 ，有两个特点
        //1. 在连续的动画过程中，前一个动画如果没有执行完毕，直接过渡到最后一个动画
        //2. 使用 7 之后，动画时长一律变成 0.5 秒
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
        //获取最终的frame - OC 中将结构体保存在字典中，存成NSValue
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        // 获取动画时长
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        toolbarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        //动画
        //UIView 的块动画，本质上是对 “核心动画” 的封装
        // 核心概念
        // 1. 通过keyPath 来指定 可动画属性的数值
        // 2. 将动画添加到 “图层”
        UIView.animateWithDuration(duration) { () -> Void in
            
            ///  设置动画曲线
            UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        //激活键盘 -->成为第一响应者
        
        //判断如果用户已经选择了照片，就不在激活键盘， 》 0 说明已经选择了照片
//        if pictureViewHeightCons?.constant == 0{
            //激活键盘
            textView.becomeFirstResponder()
//        }
    }
    
    //MARK -  创建界面
    //专门创建界面的函数
    override func loadView() {
                
        //MARK: - 不太理解这里为什么这么写
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        
        //将自动调整scrollView 的缩进取消
        automaticallyAdjustsScrollViewInsets = false
        
        prepareNav()
        
        prepareToolBar()
        
        prepareTextView()
        
        //设置照片选择器的视图
        preparePictureView()
    }
    
    //MARK: -  设置照片选择器的视图
    private func preparePictureView(){
    
        //0. 添加子控制器， - 提示： 实际开发中发现响应者链条无法正常传递，通常就是忘记添加子控制器
        // storyboard 中有一个 containerView ,纯代码中没有这个控件
        // 本质上就是一个 UIView 
        // 它做了两件事
        //1. addSubview(vc.view)
        //2. addChildViewController
        
        // 1.添加视图
        
        addChildViewController(pictureSelectorVC)
        
        view.insertSubview(pictureSelectorVC.view, belowSubview: toolBar)
        
        // 2.自动布局
        let size = UIScreen.mainScreen().bounds.size
        let w = size.width
        let h = size.height * 0.6
        
        let cons = pictureSelectorVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: h))
        
        //记录照片视图的高度约束
        pictureViewHeightCons = pictureSelectorVC.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        printLog(pictureViewHeightCons)
        
    }
    
    
    //MARK: - 设置文本视图
    private func prepareTextView(){
    
        //1. 添加
        view.addSubview(textView)
//        textView.text = "分享新鲜事..."
        
        //MARK: - topLayoutGuide 重点
        
        //2. 自动布局
        textView.translatesAutoresizingMaskIntoConstraints = false
        
        //只有添加了  topLayoutGuide 占位的文字才会显示出来，因为这是布局的问题，否则就会从最上面算起
        let viewDict:[String:AnyObject] = ["top":topLayoutGuide,"tb":toolBar,"tv":textView]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]", options: [], metrics: nil, views: viewDict))
        
        //定义textView 和toolbar 之间的约束
        textViewBootomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        
        view.addConstraint(textViewBootomCons!)
        
        textView.addSubview(placeholderLabel)
        
        placeholderLabel.frame = CGRect(origin: CGPoint(x: 5, y: 8), size: placeholderLabel.bounds.size)
        
        //设置长度提示标签 -textView 继承自 UIScrollerView 添加自动约束相当的麻烦
        // 注意： 添加到view 上
        view.addSubview(lengthTipLabel)
        lengthTipLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -HMStatusCellMargin, y: -HMStatusCellMargin))
    }
    
    //MARK: -  设置工具栏
    private func prepareToolBar(){
        
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        view.addSubview(toolBar)
        // 设置自动布局
        let w:CGFloat = UIScreen.mainScreen().bounds.width
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: 44))
        
        //记录底部约束
        toolbarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        printLog(toolbarBottomCons)
        //定义按钮数组
        let itemSettings = [["imageName":"compose_toolbar_picture","action":"selectPicture"],
        ["imageName":"compose_mentionbutton_background"],
        ["imageName":"compose_trendbutton_background"],
        ["imageName":"compose_emoticonbutton_background","action":"switchEmoticonKeyboard"],
        ["imageName":"compose_addbutton_background"]
        ]
        // 添加按钮
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings{
            
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["action"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }

    //MARK -  设置导航栏
    private func prepareNav(){
   
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        
        // 禁用发送按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        let titleLbal = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fonSize: 14)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.userAccount?.name, color: UIColor.lightGrayColor(), fonSize: 12)
        
        titleView.addSubview(titleLbal)
        titleView.addSubview(nameLabel)
        
        titleLbal.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }
    
    //懒加载 toolbar
    private lazy var toolBar = UIToolbar()
    
    //MARK: - 懒加载控件
    ///  文本视图
    private lazy var textView:UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.delegate = self
        // 允许垂直拖拽
        tv.alwaysBounceVertical = true
        
        // 拖拽 关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return tv
    }()
    
    // 懒加载 UILabel  
    private lazy var placeholderLabel:UILabel = UILabel(title: "分享新鲜事...", color: UIColor.darkGrayColor(), fonSize: 18)
    
    /// 长度标签
    private lazy var lengthTipLabel:UILabel = UILabel(title: "", color: UIColor.lightGrayColor(), fonSize: 12)
    
    //MARK: - 懒加载照片选择器视图
    private lazy var pictureSelectorVC = PictureSelectorViewController()
    
}








